import json

from django.contrib.auth.models import User
from django.http import JsonResponse

# Create your views here.

from message import models
from message.models import message
import time,datetime
# 返回主页
from usermanage.models import Follow


class message:

    # 返回用户列表页面
    @staticmethod
    def get_back(request):
        if request.method == 'POST':
            return JsonResponse({
                "error_code": 0,
                "message": "return success"
            })

    # 显示用户列表
    @staticmethod
    def notes(request):
        if request.method == 'POST':
            users = []
            follow = models.Follow.objects.filter(follower_id=request.user.id)
            for u in follow:
                tmp_dic = {}
                tmp_dic['user_id'] = u.followed_id
                tmp_user = models.UserInfo.objects.get(id=u.followed_id)
                tmp_dic['username'] = tmp_user.user.username
                users.append(tmp_dic)
            ans_list = {'users_list': users}
            return JsonResponse(ans_list)

    @staticmethod
    def get_chat(request):
        if request.method == 'POST':
            # 获取聊天记录
            data = json.loads(request.body)
            sender = models.UserInfo.objects.get(user=request.user)
            # sender = models.UserInfo.objects.get(user__username='xzb')
            recipient = models.UserInfo.objects.get(user_id=data.get('user_id'))
            AtoB = models.message.objects.filter(sender=sender, recipient=recipient, sender_can_see=True)
            BtoA = models.message.objects.filter(sender=recipient, recipient=sender, recipient_can_see=True)
            all = AtoB.union(BtoA).order_by('send_at')
            all_list = []
            for i in all:
                i_dic = {'sender': i.sender.user.username, 'recipient': i.recipient.user.username,
                         'messages': i.messages, 'send_at': i.send_at, 'message_id': i.id}
                if i.recipient.user.id == request.user.id:
                    i_dic['unread'] = False
                else:
                    i_dic['unread'] = i.unread
                all_list.append(i_dic)
            return JsonResponse({
                "all_list": all_list,
            })

    @staticmethod
    def chat(request):
        if request.method == 'POST':
            # 聊天记录上传
            data = json.loads(request.body)
            try:
                userid = data.get('user_id')
                user = models.User.objects.get(id=userid)
                recipient = models.UserInfo.objects.get(user=user)
            except Exception as e:
                return JsonResponse({
                    "status": 2,
                    "message": "接收用户不存在"
                })
            try:
                sender = models.UserInfo.objects.get(user=request.user)
                # sender = models.UserInfo.objects.get(user__username='xzb')
            except Exception as e:
                return JsonResponse({
                    "status": 3,
                    "message": "发送用户不存在"
                })
            try:
                content = data.get('message')
                models.refuse_message.objects.filter(refused__user_id=sender.user_id).get(
                    refuser__user_id=recipient.user_id)
            except Exception as e:
                models.message.objects.create(
                    sender=sender,
                    recipient=recipient,
                    messages=content,
                )
                return JsonResponse({
                    "error_code": 0,
                    "message": "send success"
                })
            return JsonResponse({
                "status": 5,
                "message": "message be refused"
            })

    @staticmethod
    def del_chat(request):
        if request.method == 'POST':
            data = json.loads(request.body)
            delete_user = models.UserInfo.objects.get(user=request.user)
            try:
                messages_obj = models.message.objects.get(id=data.get('message_id'))
                if delete_user.id == messages_obj.sender_id:
                    models.message.objects.filter(id=data.get('message_id')).update(sender_can_see=False)
                if delete_user.id == messages_obj.recipient_id:
                    models.message.objects.filter(id=data.get('message_id')).update(recipient_can_see=False)
            except Exception as e:
                return JsonResponse({
                    "status": 4,
                    "message": "当前消息不存在"
                })
            return JsonResponse({
                "status": 0,
                "message": "delete message success"
            })

    @staticmethod
    def refuse_chat(request):
        data = json.loads(request.body)
        refuser = models.UserInfo.objects.get(user=request.user)
        # refuser = models.UserInfo.objects.get(user__username='yzb')
        try:
            # refused = models.UserInfo.objects.get(user__username='xzb')
            refused = models.UserInfo.objects.get(user_id=data.get('refused_id'))
        except Exception as e:
            return JsonResponse({
                "status": 2,
                "message": "拒绝用户不存在"
            })
        try:
            models.refuse_message.objects.get(
                refuser=refuser,
                refused=refused,
            )
        except Exception as e:
            models.refuse_message.objects.create(
                refuser=refuser,
                refused=refused,
            )
            return JsonResponse({
                "status": 0,
                "message": "已拒收该用户消息"
            })
        else:
            return JsonResponse({
                "status": 8,
                "message": "已拒收"
            })

    @staticmethod
    def accept_chat(request):
        data = json.loads(request.body)
        refuser = models.UserInfo.objects.get(user=request.user)
        try:
            refused = models.UserInfo.objects.get(user_id=data.get('refused_id'))
        except Exception as e:
            return JsonResponse({
                "status": 2,
                "message": "拒绝用户不存在"
            })
        try:
            list = models.refuse_message.objects.filter().values('refused_id')
            print(list)
            refuse_message_obj = models.refuse_message.objects.get(
                refuser=refuser,
                refused=refused,
            )
            print("xx")
            refuse_message_obj.delete()
        except Exception as e:
            return JsonResponse({
                "status": 6,
                "message": "已同意"
            })
        return JsonResponse({
            "status": 0,
            "message": "已同意接收该用户消息"
        })

    @staticmethod
    def refuse_notes(request):
        if request.method == 'POST':
            users = []
            refuses = models.refuse_message.objects.filter(refuser__user_id=request.user.id)
            for r in refuses:
                tmp_dic = {}
                tmp_dic['user_id'] = r.refused_id
                tmp_user = models.UserInfo.objects.get(id=r.refused_id)
                tmp_dic['username'] = tmp_user.user.username
                users.append(tmp_dic)
            ans_list = {'users_list': users}
            return JsonResponse(ans_list)

    @staticmethod
    def mmm(request):
        data = json.loads(request.body)
        User_obj = models.UserInfo.objects.filter(id=1).first()
        print(User_obj.id+1)
        return JsonResponse({})
